import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class IQClearTexField extends StatefulWidget {
  const IQClearTexField({
    super.key,
    this.hintText,
    this.maxLines,
    this.keyboardType,
    this.autofocus = false,
    this.inputFormatters,
    this.controller,
    this.enabled = true,
    this.onChanged,
    this.contentPadding =
        const EdgeInsets.only(left: 16, right: 8, top: 12, bottom: 12),
  });
  final String? hintText;
  final int? maxLines;
  final TextInputType? keyboardType;
  final bool autofocus;
  final List<TextInputFormatter>? inputFormatters;
  final TextEditingController? controller;
  final bool enabled;
  final void Function(String)? onChanged;
  final EdgeInsets contentPadding;
  @override
  State<IQClearTexField> createState() => _IQClearTexFieldState();
}

class _IQClearTexFieldState extends State<IQClearTexField> {
  TextEditingController controller = TextEditingController();
  @override
  void initState() {
    controller = widget.controller ?? controller;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    TextInputType? keyboardType = widget.keyboardType;
    if (keyboardType == null && widget.maxLines == null) {
      keyboardType = TextInputType.multiline;
    }
    return TextFormField(
      controller: controller,
      maxLines: widget.maxLines,
      keyboardType: keyboardType,
      inputFormatters: widget.inputFormatters,
      enabled: widget.enabled,
      onChanged: widget.onChanged,
      decoration: InputDecoration(
        hintText: widget.hintText,
        isCollapsed: true,
        border: const OutlineInputBorder(borderSide: BorderSide.none),
        contentPadding: widget.contentPadding,
        suffixIcon: Builder(builder: (context) {
          return ValueListenableBuilder(
            builder: (context, value, child) {
              return Offstage(
                offstage: value.text.isEmpty,
                child: GestureDetector(
                  onTap: () {
                    controller.clear();
                    widget.onChanged?.call('');
                  },
                  child: const Icon(
                    Icons.clear,
                    size: 20,
                  ),
                ),
              );
            },
            valueListenable: controller,
          );
        }),
      ),
      autofocus: widget.autofocus,
    );
  }
}
